layui.use(['table', 'admin', 'ax'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;

    /**
     * 出库订单表管理 Outbound Order Management
     */
    var OutOrder = {
        tableId: "outOrderTable"
    };

    /**
     * 出库订单明细表管理 Outbound Order Details Management
     */
    var OutOrderDetailed = {
        tableId: "outOrderDetailedTable"
    };

    /**
     * 初始化表格的列 Initialize Table Columns
     */
    OutOrder.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: '主键id'},
            {field: 'expressDelivery', title: '快递单号', style:'color: #2b85e4;font-weight: 600;',width:150},
            {field: 'customerNumber', title: '客户单号', style:'color: #2b85e4;font-weight: 600;',width:150},
            {field: 'outOrderStatus', title: '单据状态', templet: '#outOrderStatusTpl', event: 'outOrderStatusSign'},
            {field: 'setMentiontime', title: '发货日期', style:'font-weight: 600;'},
            {field: 'createUserName', title: '制单人员'},
            {field: 'getUnit', title: '卸货单位', style:'font-weight: 600;',width:180},
            {field: 'getLocation', title: '卸货地点',width:250},
            {field: 'outWay', title: '出库方式'},
            {field: 'note', title: '备注'},
            {field: 'getUnitId', title: '卸货单位ID'},
            {field: 'kilometer', title: '公里数'},
            {field: 'storehouseName', title: '仓库名称'},
            {field: 'outCustomerName', title: '客户名称'},
            {field: 'outOrderNumber', title: '出库订单号'},
            {field: 'setUnit', title: '装货单位'},
            {field: 'setLocation', title: '装货地址'},
            {field: 'createTime', title: '制单时间'},
            {field: 'submitTime', title: '提交时间'},
            {field: 'submitterName', title: '提交人员'},
            {fixed: 'right',width: 90,align: 'center', toolbar: '#tableBar', title: '操作'}
        ]];
    };

    /**
     * 点击查询按钮 Click Search Button
     */
    OutOrder.search = function () {
        var queryData = {};
        queryData['condition'] = $("#condition").val();
        queryData['outCustomerId'] = $("#outCustomerId").val();
        queryData['outStorehouseId'] = $("#outStorehouseId").val();
        table.reload(OutOrder.tableId, {
            where: queryData, page: {curr: 1},
            done:function () {
            }
        });
    };
    OutOrder.toJSTOutOrder = function () {
        // var ajax = new $ax(Feng.ctxPath + "/outOrder/getJSTOutOrder" );  // Create AJAX request
        // var result = ajax.start();  // Start AJAX request
        // console.log(result)  // Log result
        // Feng.success("拉取成功!");  // Success message: Pull successful!
        window.location.href = Feng.ctxPath + '/whOutOrder/toJSTOutOrder';
    };

    // 导入excel按钮点击事件 Import Excel Button Click Event
    OutOrder.importExcel = function () {
        layer.open({
            type: 2,
            title: '出库订单导入',
            area: ['1000px', '550px'],
            anim: 5,
            content: Feng.ctxPath + '/outOrder/toimportExcel',
            end: function () {
                table.reload(OutOrder.tableId);
                outOrder(null);
                OutOrder.search();
            }
        });
    };

    // 导入excel按钮点击事件
    OutOrder.importExcel_ha = function () {
        layer.open({
            type: 2,
            title: '出库订单导入_恒安',
            area: ['1000px', '550px'],
            anim: 5,
            content: Feng.ctxPath + '/outOrder/toimportExcel_ha',
            end: function () {
                table.reload(OutOrder.tableId);
                outOrder(null);
                OutOrder.search();
            }
        });
    };

    /**
     * 弹出添加对话框 Open Add Dialog
     */
    OutOrder.openAddDlg = function () {
        window.location.href = Feng.ctxPath + '/outOrder/add';
    };

    /**
     * 弹出添加对话框
     */
    OutOrder.openAddDlg = function () {
        window.location.href = Feng.ctxPath + '/outOrder/add';
    };

    /**
     * 导出excel按钮 Export Excel Button
     */
    OutOrder.exportExcel = function () {
        var checkRows = table.checkStatus(OutOrder.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };

    /**
     * 点击编辑 Click Edit
     *
     * @param data 点击按钮时候的行数据 Row data when button is clicked
     */
    OutOrder.openEditDlg = function (data) {
        window.location.href = Feng.ctxPath + '/outOrder/edit?id=' + data.id;
    };

    /**
     * 点击删除 Click Delete
     *
     * @param data 点击按钮时候的行数据 Row data when button is clicked
     */
    OutOrder.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/outOrder/delete", function (data) {
                Feng.success("删除成功!");
                table.reload(OutOrder.tableId);
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("是否删除?", operation);
    };

    // 渲染表格 Render table
    var tableResult = table.render({
        elem: '#' + OutOrder.tableId,
        url: Feng.ctxPath + '/whOutOrder/list',
        page: true,
        limit: 30,
        height: 410,
        toolbar: '#demotoolbarfrom',
        cellMinWidth: 100,
        cols: OutOrder.initColumn()
    });

    // 批量提交 Batch Submit
    OutOrder.submit = function () {
        var checkStatus = table.checkStatus('outOrderTable');
        data = checkStatus.data;
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
                ids.push(data[i].id);
            }
            layer.confirm('是否提交选中订单?', function(index){
                layer.close(index);
                var msg;
                $.ajax({
                    url:Feng.ctxPath + "/outOrder/submits?ids="+ids,
                    cache: false,
                    dataType:"json",
                    beforeSend:function(){
                        //弹出加载中 Show loading message
                        msg = layer.msg('提交中。。。请耐心等待', {
                            icon: 16,
                            shade: [0.2,'#000'], //0.1透明度的白色背景
                            time: false
                        });
                    },
                    success:function(data){
                        console.log(data)
                        layer.close(msg);
                        if (data.success) {
                            Feng.success("提交成功!");
                            table.reload(OutOrder.tableId);
                        } else {
                            if (data.message !=null &&data.message!='') {
                                var msg2 =  layer.open({
                                    title: '提示' ,
                                    content: data.message,
                                    btn: ['确定'],
                                    yes: function (){
                                        layer.close(msg2);
                                        table.reload(OutOrder.tableId);
                                    }
                                });
                            } else {
                                Feng.error("提交失败！");
                                table.reload(OutOrder.tableId);
                            }
                        }
                    },
                    error:function(data){
                        layer.close(msg);
                        Feng.error("提交失败！" + data.responseJSON.message)
                        table.reload(OutOrder.tableId);
                    }
                })
            });
        } else {
            layer.alert('请至少选中一条数据');
        }
    };


    // 批量提交
    OutOrder.submitHshn = function () {
        var checkStatus = table.checkStatus('outOrderTable');
        data = checkStatus.data;
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
                ids.push(data[i].id);
            }
            layer.confirm('是否提交选中订单?', function(index){
                layer.close(index);
                var msg;
                $.ajax({
                    url:Feng.ctxPath + "/outOrder/submitsHshnWh?ids="+ids,
                    cache: false,
                    dataType:"json",
                    beforeSend:function(){
                        //弹出加载中
                        msg = layer.msg('提交中。。。请耐心等待', {
                            icon: 16,
                            shade: [0.2,'#000'], //0.1透明度的白色背景
                            time: false
                        });
                    },
                    success:function(data){
                        console.log(data)
                        layer.close(msg);
                        if (data.success) {
                            Feng.success("提交成功!");
                            table.reload(OutOrder.tableId);
                        } else {
                            if (data.message !=null &&data.message!='') {
                                var msg2 =  layer.open({
                                    title: '提示' ,
                                    content: data.message,
                                    btn: ['确定'],
                                    yes: function (){
                                        layer.close(msg2);
                                        table.reload(OutOrder.tableId);
                                    }
                                });
                            } else {
                                Feng.error("提交失败！");
                                table.reload(OutOrder.tableId);
                            }
                        }
                    },
                    error:function(data){
                        layer.close(msg);
                        Feng.error("提交失败！" + data.responseJSON.message)
                        table.reload(OutOrder.tableId);
                    }
                })
            });
        } else {
            layer.alert('请至少选中一条数据');
        }
    };

    // 批量作废
    OutOrder.cancel = function () {
        var checkStatus = table.checkStatus('outOrderTable');
        data = checkStatus.data;
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
                ids.push(data[i].id);
            }
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/outOrder/cancel?ids="+ids, function (data) {
                    Feng.success("作废成功!");
                    table.reload(OutOrder.tableId);
                }, function (data) {
                    Feng.error("作废失败!" + data.responseJSON.message + "!");
                });
                ajax.start();
            };
            Feng.confirm("是否作废选中订单?", operation);
        } else {
            layer.alert('请至少选中一条数据');
        }
    };

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        OutOrder.search();
    });
    // 搜索按钮点击事件
    $('#btnJSTOutOrder').click(function () {
        // alert(1111)
        OutOrder.toJSTOutOrder();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        // alert(222)
        OutOrder.openAddDlg();
    });

    // 导出excel
    $('#btnExp').click(function () {
        OutOrder.exportExcel();
    });

    // 导入excel
    $('#btnExpimport').click(function () {
        OutOrder.importExcel();
    });

    // 导入excel
    $('#btnExpimport_ha').click(function () {
        OutOrder.importExcel_ha();
    });

    // 批量提交
    $('#btnSubmits').click(function () {
        OutOrder.submit();
    });

    // 批量提交
    $('#hshnBtnSubmits').click(function () {

        OutOrder.submitHshn();
    });

    // 批量作废
    $('#btnCancel').click(function () {
        OutOrder.cancel();
    });

    // 工具条点击事件
    table.on('tool(' + OutOrder.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            OutOrder.openEditDlg(data);
        }else if (obj.event === 'outOrderStatusSign' && data.outOrderStatus == '驳回'){
            var index = layer.open({
                title: '审核详情：',
                type: 1,
                title: false, //不显示标题栏
                closeBtn: false,
                shade: 0.3,
                area: '300px;',
                content: "<div style='padding: 50px; word-wrap: break-word;word-break: break-all;overflow: hidden; background-color: #000000; color: #fff;line-height: 22px;  font-weight: 300;'>审核人："+data.examineName+"<br><br>审核时间："+data.examineTime+"<br><br>批注：<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+data.returnNote+"</div>",
                btn: ['确定'] ,
                btnAlign: 'c' ,//按钮居中
                yes: function(){
                    layer.close(index);
                }
            });
        }
    });

    /**
     * 初始化表格的列
     */
    OutOrderDetailed.initColumn = function () {
        return [[
            {field: 'id', hide: true, title: '主键'},
            {field: 'detailedFactory', title: '工厂号', hide: true},
            {field: 'detailedGoodsname', sort: true, title: '商品名称', style:'background-color: #dbf1e1;font-weight: 600;',width: 200},
            {field: 'detailedGoodscode', sort: true, title: '商品编号', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'goodsNo', title: '货号', style:'background-color: #dbf1e1;font-weight: 600;', totalRowText: '合计：'},

            {field: 'detailedNumber', sort: true, title: '数量', totalRow: true, style:'background-color: #dbf1e1;font-weight: 600;'},

            {field: 'kcCount', title: '库存', style:'background-color: #dbf1e1;font-weight: 600;',width: 140},
            {field: 'cckcCount', title: '存储位库存', style:'background-color: #dbf1e1;font-weight: 600;',width: 140},
            {field: 'jhkcCount', title: '拣货位位库存', style:'background-color: #dbf1e1;font-weight: 600;',width: 140},
            {field: 'djhCount', title: '占用库存', style:'background-color: #dbf1e1;font-weight: 600;',width: 140},
            {field: 'detailedDate', sort: true, title: '生产日期', style:'background-color: #dbf1e1;font-weight: 600;',width: 140},
            {field: 'detailedBatchnumber', sort: true, title: '批次', style:'background-color: #dbf1e1;font-weight: 600;',width: 140},
            {field: 'detailedPrice', title: '单价'},
            {field: 'detailedMoney', sort: true, title: '金额', totalRow: true},
            {field: 'detailedOutVolume', sort: true, title: '体积', totalRow: true},
            {field: 'detailedOutWeight', sort: true, title: '重量', totalRow: true},
            {field: 'detailedLargeclass', title: '大类'},
            {field: 'detailedGoodstype', title: '类别', hide: true},
            {field: 'goodsUnit', title: '单位'},
            {field: 'detailedPacking', title: '包装'},
            {field: 'goodsSpecs', title: '规格'},
            {align: 'center', toolbar: '#tableBarDetailed', title: '操作',fixed: 'right',width: 200}
        ]];
    };


    // 单击行事件
    table.on('row(' + OutOrder.tableId + ')', function (obj) {
        var data = obj.data;
        $('div[lay-id="' + OutOrder.tableId + '"]').find(".layui-table-body tr ").attr({ "style": "background:#FFFFFF" });//其他tr恢复原样
        $('div[lay-id="' + OutOrder.tableId + '"]').find(obj.tr.selector).attr({ "style": "background:#e6e6e6" });//改变当前tr颜色
        outOrder(data);
    });

    function outOrder(data){
        var outOrderNumber;
        if (data!=null) {
            $("#detailedOutNumber").val(data.outOrderNumber);
            outOrderNumber = data.outOrderNumber;
        } else {
            outOrderNumber = 'nodata';
        }
        /**
         * Render product details table 渲染商品明细表格
         */
        var tableResult = table.render({
            elem: '#' + OutOrderDetailed.tableId,
            url: Feng.ctxPath + '/whOutOrderDetailed/list?detailedOutNumber=' + outOrderNumber,
            page: true,
            limit: 30,
            height: 400,
            toolbar: '#toolbarfromDetailed',
            cellMinWidth: 100,
            totalRow: true ,//开启合计行
            cols: OutOrderDetailed.initColumn()
        });

        /**
         * Click search button 点击查询按钮
         */
        OutOrderDetailed.search = function () {
            var queryData = {};
            queryData['condition'] = $("#condition2").val();
            table.reload(OutOrderDetailed.tableId, {
                where: queryData, page: {curr: 1},
                done:function () {
                    // Search button click event 搜索按钮点击事件
                    $('#btnSearchDetailed').click(function () {
                        OutOrderDetailed.search();
                    });
                    // Add button click event 添加按钮点击事件
                    $('#btnAddDetailed').click(function () {
                        OutOrderDetailed.addDetailed();
                    });
                }
            });
        };

        OutOrderDetailed.addDetailed = function () {
            layer.open({
                type: 2,
                title: '明细录入',
                area: ['1000px', '750px'],
                anim: 5,
                content: Feng.ctxPath + '/outOrderDetailed/add?detailedOutNumber=' + data.outOrderNumber+"&outCustomerId="+data.outCustomerId,
                end: function () {
                    outOrder(data);
                }
            });
        };

        // Toolbar click event 工具条点击事件
        table.on('tool(' + OutOrderDetailed.tableId + ')', function (obj) {
            var data2 = obj.data;
            var layEvent = obj.event;

            if (layEvent === 'editDetailed') {
                OutOrderDetailed.openEditDlg(data2);
            } else if (layEvent === 'deleteDetailed') {
                OutOrderDetailed.onDeleteItem(data2);
            } else if (layEvent === 'moveDetailed') {
                OutOrderDetailed.openMoveDlg(data2);
            }
        });

        // 修改按钮点击事件
        OutOrderDetailed.openEditDlg = function (data2) {
            layer.open({
                type: 2,
                title: '明细修改',
                area: ['1000px', '750px'],
                anim: 5,
                content: Feng.ctxPath + '/outOrderDetailed/edit?id='+data2.id+"&detailedOutNumber="+data.outOrderNumber+"&outCustomerId="+data.outCustomerId,
                end: function () {
                    outOrder(data);
                }
            });
        };

        // 修改按钮点击事件
        OutOrderDetailed.openMoveDlg = function (data2) {
            layer.open({
                type: 2,
                title: '移动明细到其他订单',
                area: ['500px', '950px'],
                anim: 5,
                content: Feng.ctxPath + '/outOrderDetailed/moveOpen?id='+data2.id,
                end: function () {
                    OutOrderDetailed.search();
                }
            });
        };

        // 删除按钮点击事件
        OutOrderDetailed.onDeleteItem = function (data2) {
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/outOrderDetailed/delete", function (data2) {
                    Feng.success("删除成功!");
                    outOrder(data);
                }, function (data) {
                    Feng.error("删除失败!" + data2.responseJSON.message + "!");
                });
                ajax.set("id", data2.id);
                ajax.start();
            };
            Feng.confirm("是否删除?", operation);
        };

        // 搜索按钮点击事件
        $('#btnSearchDetailed').click(function () {
            OutOrderDetailed.search();
        });

        $('#btnAddDetailed').click(function () {
            OutOrderDetailed.addDetailed();
        });

    }

});
